import style from './Message_rider.module.css'
import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
import { Input, Cell, Button } from 'react-vant';
import { useSelector } from 'react-redux';
import { NavBar, Space } from 'antd-mobile'
import { SearchOutline, MoreOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom';

export default function Chat() {
    const role = useSelector(a => a.ku.user_id)
    const Navigate = useNavigate()

    const [userInput, setUserInput] = useState("")
    const [userList, setUserList] = useState([])
    const [userList2, setUserList2] = useState([])
    const key = useSelector(a => a.user.userObj.key)

    useEffect(() => {
        const socket = io('http://47.116.116.42:3000', {
            transports: ['websocket']
        });

        socket.emit('if', role);

        if (userList.length > 0) {
            socket.on('connect', () => {
                console.log('服务器连接成功');

                // 发送消息到服务器
                socket.emit('message', userList);
                setUserList([])
            });

        }

        socket.on('init', (data) => {
            // console.log('服务器发送过来的数据:', data);
            setUserList2(data)
        });

        // 监听与服务器的断开连接
        // socket.on('disconnect', () => {
        //     console.log('服务器断开连接');
        // });

        // 在组件卸载时关闭Socket连接
        // return () => {
        //     socket.disconnect();
        // };
    }, [userList]);

    const right = (
        <div style={{ fontSize: 24 }}>
            <Space style={{ '--gap': '16px' }}>
                <SearchOutline />
                <MoreOutline />
            </Space>
        </div>
    )

    const back = () => {
        Navigate("/rider/chathome")
    }

    const add_userInput = () => {
        const socket = io('http://47.116.116.42:3000', {
            transports: ['websocket']
        });

        socket.on('init', (data) => {
            console.log('服务器发送过来的数据:', data);

            setUserList2(data)
        });

        let new_list = [...userList]
        new_list.push({ "yi": userInput, "er": new Date, "san": "rider", "si": "https://images.unsplash.com/photo-1548532928-b34e3be62fc6?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ" })
        setUserList(new_list)
        setUserInput("")
    }

    const render_userList = () => {
        return userList2.map(item => {
            return <div key={item._id} className={item.san == key ? style.use_char_box_right : style.use_char_box}>
                <img src={item.si} alt="" className={style.box_img} />
                <div className={style.name}>{item.san}</div>
                <div className={item.san == key ? style.box_big_right : style.box_big}>
                    {item.yi}
                </div>
            </div>
        })
    }

    return (
        <div>
            <NavBar right={right} onBack={back}>
                聊天
            </NavBar>

            <div>
                {render_userList()}
            </div>

            <Cell>
                <Input
                    style={{ position: "fixed", bottom: "20px", width: "380px" }}
                    prefix="💁"
                    suffix={<Button size="small" type="primary" onClick={() => { add_userInput() }}>发送</Button>}
                    placeholder="请输入短信验证码"
                    value={userInput}
                    onChange={(value) => {
                        setUserInput(value)
                    }}
                />
            </Cell>
        </div>
    )
}
